import { t } from 'i18next'
import React, { useRef, useState } from 'react'
import { Modal, Input, Button, Space } from '@kedacom/react-next'
import requestMeeting from '@/plugins/axios'
import { CheckWrap, StyledBtn } from './style'

/** 校验动态密码弹窗 */
export const fetchCheckDynamicPassword = async (password: string) =>
	requestMeeting<boolean>({
		url: '/mcc/check_dynamic_password',
		method: 'get',
		params: { password },
	}).then((res) => res)

export interface AuthenticationCheckProps {
	open: boolean
	setOpen: (val: boolean) => void
	callBack?: Function
}

export default function AuthenticationCheck(props: AuthenticationCheckProps) {
	const { open, setOpen, callBack } = props
	const [isError, setIsError] = useState(false)
	const [isLimit, setIsLimit] = useState(false)
	const [value, setValue] = useState<string>('')
	const [count, setCount] = useState<number>(0)
	const authenticationPassed = useRef(false)
	const handleOk = () => {
		if (value.trim() !== '') {
			fetchCheckDynamicPassword(value).then((res) => {
				if (res.success) {
					if (res.data) {
						setIsError(false)
						authenticationPassed.current = true
						handleCancel()
					} else {
						setIsError(true)
						let newCount = count + 1
						setCount(newCount)
						if (newCount > 2) {
							setIsLimit(true)
						}
					}
				}
			})
		}
	}
	const handleCancel = () => {
		setOpen(false)
		setIsError(false)
		setValue('')
		setCount(0)
		callBack?.(authenticationPassed.current)
	}
	return (
		<Modal
			open={open}
			title={t('输入动态口令')}
			width="408px"
			height="278px"
			footer={
				isLimit ? (
					<StyledBtn>
						<Space>
							<Button onClick={handleCancel}>{t('关闭')}</Button>
						</Space>
					</StyledBtn>
				) : (
					<StyledBtn>
						<Space>
							<Button onClick={handleOk}>{t('确定')}</Button>
							<Button onClick={handleCancel}>{t('取消')}</Button>
						</Space>
					</StyledBtn>
				)
			}
			onCancel={handleCancel}
		>
			<CheckWrap>
				<div className="label">{t('动态口令')}</div>
				<Input
					placeholder={t('请输入动态口令')}
					width="200px"
					value={value}
					onChange={(e, val) => {
						setValue(val)
					}}
				/>
				{isError && (
					<div className="error-msg">
						{isLimit
							? t('口令输入错误3次，请稍后尝试')
							: t('口令输入错误{{num}}次，请重新尝试。', { num: count })}
					</div>
				)}
			</CheckWrap>
		</Modal>
	)
}
